﻿using RabbitMQ.Client.Events;
using RabbitMQ_Common;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace RabbitMQ_Consumer.Topic
{
    public class TopicConsumer
    {
        public static void ConsumerMessage()
        {
            try
            {
                var connection = RabbitMQHelper.GetConnection();
                var channel = connection.CreateModel();

                //声明交换机，direct(路由)模式
                channel.ExchangeDeclare("topic_exchange", "topic", true, false, null);

                //声明队列
                channel.QueueDeclare("topic_queue1", true, false, false, null);
                channel.QueueDeclare("topic_queue2", true, false, false, null);
                channel.QueueDeclare("topic_queue3", true, false, false, null);

                //队列绑定交换机
                channel.QueueBind("topic_queue1", "topic_exchange", "user.insert", null);
                channel.QueueBind("topic_queue2", "topic_exchange", "user.update", null);
                channel.QueueBind("topic_queue3", "topic_exchange", "user.*", null);

                //设置限流机制
                //prefetchSize，消息本身的大小 如果设置为0  那么表示对消息本身的大小不限制
                //prefetchCount，告诉rabbitmq不要一次性给消费者推送大于N个消息
                //global，是否将上面的设置应用于整个通道，false表示只应用于当前消费者
                channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (model, ea) =>
                {
                    //Thread.Sleep(1000);
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body.ToArray());
                    var routingkey = ea.RoutingKey;

                    //DeliveryTag 消息ID ulong
                    //false 是否批量确认，true 小于DeliveryTag的全部确认
                    channel.BasicAck(ea.DeliveryTag, false);
                    Console.WriteLine($"TopicConsumer message is {message},routingkey=> {routingkey}");
                };
                channel.BasicConsume("topic_queue1", false, "", false, false, null, consumer);
                channel.BasicConsume("topic_queue3", false, "", false, false, null, consumer);
            }
            catch (Exception e)
            {
                Console.WriteLine($"TopicConsumer Consume Failed:{e.Message}");
            }
            
        }
    }
}
